package ai.peanut.selfbase.common.security.shiro;

import ai.peanut.selfbase.modules.menu.entity.Menu;
import ai.peanut.selfbase.modules.menu.service.IMenuService;
import ai.peanut.selfbase.modules.user.entity.User;
import ai.peanut.selfbase.modules.user.pojo.UserDto;
import ai.peanut.selfbase.modules.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SystemAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    private IUserService iUserService ;
    @Autowired
    private IMenuService iMenuService ;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取唯一的用户  可以是多个
        UserDto userDto = (UserDto)principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//        Set<String> set = new HashSet<>() ;
//        set.add("role1");
//        set.add("role2");
//        authorizationInfo.setRoles(set);

        Set<String> setp = new HashSet<>() ;
//        setp.add("user1:update");
//        setp.add("user1:add");
//        setp.add("user2:*");
        List<Menu> list = iMenuService.selectMenuListByUserId(userDto.getId());
        if( list != null && list.size() > 0 ){
            for( Menu m : list ) {
               if( (m.getMenuType() == 2 || m.getMenuType() == 3) &&
                       StringUtils.isNotBlank(m.getPermission()) ) {
                   setp.add( m.getPermission() ) ;
               }
            }
        }
        authorizationInfo.setStringPermissions(setp);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String loginname = (String)token.getPrincipal();  //得到用户名
        String password = new String((char[])token.getCredentials()); //得到密码

        UserDto user = iUserService.getUserByLoginName(loginname) ;

        if(user == null) {
            throw new UnknownAccountException("账号不存在"); //如果用户名错误
        }

        //账号锁定
        if(user.getLoginFlag() == 0){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        if(user.getDelFlag() == 0){
            throw new DisabledAccountException ("账号已删除,请联系管理员");
        }

        //如果身份认证验证成功，返回一个AuthenticationInfo实现；
        UserDto userDto = new UserDto() ;
        BeanUtils.copyProperties( user , userDto );
        return new SimpleAuthenticationInfo(userDto, user.getPassword(),
                ByteSource.Util.bytes(ShiroUtils.generatorSale(
                        user.getLoginName(), userDto.getId().toString() , user.getSalt())), getName());

    }

    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
        shaCredentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName);//md5
        shaCredentialsMatcher.setHashIterations(ShiroUtils.hashIterations);//cishu
        shaCredentialsMatcher.setStoredCredentialsHexEncoded(true);//  默认true 16进制  base64
        super.setCredentialsMatcher(shaCredentialsMatcher);
    }
}
